<template>
  <div class="ware-in-out-type-summary">
    <!-- 时间筛选 -->
    <el-card class="time-filter-card">
      <div class="time-filter">
        <el-button
          v-for="timeFilter in timeFilters"
          :key="timeFilter.key"
          :type="selectedTimeFilter === timeFilter.key ? 'primary' : 'default'"
          size="small"
          @click="selectTimeFilter(timeFilter.key)"
        >
          {{ timeFilter.label }}
        </el-button>

        <!-- 自定义时间范围选择器 -->
        <div v-if="selectedTimeFilter === 'custom'" class="custom-time-picker">
          <el-date-picker
            v-model="customDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            size="small"
            @change="handleCustomDateChange"
          />
          <el-button type="primary" size="small" @click="searchWithCustomDate">
            查询
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 入库类型汇总图表 -->
      <el-card class="chart-card">
        <template #header>
          <div class="chart-header">
            <span class="chart-title">入库类型汇总</span>
          </div>
        </template>
        <div class="chart-container">
          <div ref="inboundChart" class="chart"></div>
        </div>
      </el-card>

      <!-- 出库类型汇总图表 -->
      <el-card class="chart-card">
        <template #header>
          <div class="chart-header">
            <span class="chart-title">出库类型汇总</span>
          </div>
        </template>
        <div class="chart-container">
          <div ref="outboundChart" class="chart"></div>
        </div>
      </el-card>
    </div>

    <!-- 货品信息表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <span class="table-title">货品信息</span>
          <div class="table-actions">
            <el-button type="primary" size="small" @click="exportData">
              <el-icon><Download /></el-icon>
              导出{{
                selectedRows.length > 0
                  ? `(${selectedRows.length}条)`
                  : "(全部)"
              }}
            </el-button>
            <el-button type="primary" size="small" @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="tableDataWithSummary"
        style="width: 100%"
        border
        stripe
        v-loading="loading"
        element-loading-text="数据加载中..."
        @selection-change="handleSelectionChange"
        :row-class-name="getRowClassName"
        :cell-class-name="getCellClassName"
      >
        <!-- 货品信息列 -->
        <el-table-column
          type="selection"
          width="55"
          fixed="left"
          :selectable="isRowSelectable"
        />
        <el-table-column label="序号" width="60" fixed="left">
          <template #default="scope">
            <span
              v-if="scope.row.product_Number === '合计'"
              class="summary-text"
              >合计</span
            >
            <span v-else>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="product_Number"
          label="货品编号"
          width="90"
          fixed="left"
        >
          <template #default="scope">
            <span
              v-if="scope.row.product_Number === '合计'"
              class="summary-text"
            ></span>
            <span v-else>{{ scope.row.product_Number }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="product_Name"
          label="货品名称"
          width="90"
          fixed="left"
        >
          <template #default="scope">
            <span
              v-if="scope.row.product_Number === '合计'"
              class="summary-text"
            ></span>
            <span v-else>{{ scope.row.product_Name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="specifications"
          label="规格型号"
          width="90"
          fixed="left"
        >
          <template #default="scope">
            <span
              v-if="scope.row.product_Number === '合计'"
              class="summary-text"
            ></span>
            <span v-else>{{ scope.row.specifications }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="category_Name"
          label="货品类型"
          width="90"
          fixed="left"
        >
          <template #default="scope">
            <span
              v-if="scope.row.product_Number === '合计'"
              class="summary-text"
            ></span>
            <span v-else>{{ scope.row.category_Name }}</span>
          </template>
        </el-table-column>

        <!-- 入库类型列 -->
        <el-table-column label="入库" align="center">
          <el-table-column label="采购收货入库" align="center">
            <el-table-column
              prop="purchaseIn_TotalCount"
              label="数量"
              width="80"
              align="center"
            >
              <template #default="scope">
                <span
                  :class="{
                    'highlight-summary': scope.row.product_Number === '合计',
                  }"
                >
                  {{ formatNumber(scope.row.purchaseIn_TotalCount) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="purchaseIn_TotalAmount"
              label="金额"
              width="100"
              align="center"
            >
              <template #default="scope">
                <span
                  :class="{
                    'highlight-summary': scope.row.product_Number === '合计',
                  }"
                >
                  {{ formatCurrency(scope.row.purchaseIn_TotalAmount) }}
                </span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="销售退货入库" align="center">
            <el-table-column
              prop="salesReturnIn_TotalCount"
              label="数量"
              width="80"
              align="center"
            >
              <template #default="scope">
                <span
                  :class="{
                    'highlight-summary': scope.row.product_Number === '合计',
                  }"
                >
                  {{ formatNumber(scope.row.salesReturnIn_TotalCount) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="salesReturnIn_TotalAmount"
              label="金额"
              width="100"
              align="center"
            >
              <template #default="scope">
                <span
                  :class="{
                    'highlight-summary': scope.row.product_Number === '合计',
                  }"
                >
                  {{ formatCurrency(scope.row.salesReturnIn_TotalAmount) }}
                </span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="生产产品入库" align="center">
            <el-table-column
              prop="productionIn_TotalCount"
              label="数量"
              width="80"
              align="center"
            >
              <template #default="scope">
                <span
                  :class="{
                    'highlight-summary': scope.row.product_Number === '合计',
                  }"
                >
                  {{ formatNumber(scope.row.productionIn_TotalCount) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="productionIn_TotalAmount"
              label="金额"
              width="100"
              align="center"
            >
              <template #default="scope">
                <span
                  :class="{
                    'highlight-summary': scope.row.product_Number === '合计',
                  }"
                >
                  {{ formatCurrency(scope.row.productionIn_TotalAmount) }}
                </span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="领用退还入库" align="center">
            <el-table-column
              prop="returnIn_TotalCount"
              label="数量"
              width="80"
              align="center"
            >
              <template #default="scope">
                <span
                  :class="{
                    'highlight-summary': scope.row.product_Number === '合计',
                  }"
                >
                  {{ formatNumber(scope.row.returnIn_TotalCount) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="returnIn_TotalAmount"
              label="金额"
              width="100"
              align="center"
            >
              <template #default="scope">
                <span
                  :class="{
                    'highlight-summary': scope.row.product_Number === '合计',
                  }"
                >
                  {{ formatCurrency(scope.row.returnIn_TotalAmount) }}
                </span>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table-column>

        <!-- 出库类型列 -->
        <el-table-column label="出库" align="center">
          <el-table-column label="销售出库" align="center">
            <el-table-column
              prop="salesOut_TotalCount"
              label="数量"
              width="80"
              align="center"
            >
              <template #default="scope">
                <span
                  :class="{
                    'highlight-summary': scope.row.product_Number === '合计',
                  }"
                >
                  {{ formatNumber(scope.row.salesOut_TotalCount) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="salesOut_TotalAmount"
              label="金额"
              width="100"
              align="center"
            >
              <template #default="scope">
                <span
                  :class="{
                    'highlight-summary': scope.row.product_Number === '合计',
                  }"
                >
                  {{ formatCurrency(scope.row.salesOut_TotalAmount) }}
                </span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="生产领用出库" align="center">
            <el-table-column
              prop="productionOut_TotalCount"
              label="数量"
              width="80"
              align="center"
            >
              <template #default="scope">
                <span
                  :class="{
                    'highlight-summary': scope.row.product_Number === '合计',
                  }"
                >
                  {{ formatNumber(scope.row.productionOut_TotalCount) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="productionOut_TotalAmount"
              label="金额"
              width="100"
              align="center"
            >
              <template #default="scope">
                <span
                  :class="{
                    'highlight-summary': scope.row.product_Number === '合计',
                  }"
                >
                  {{ formatCurrency(scope.row.productionOut_TotalAmount) }}
                </span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="领用退还出库" align="center">
            <el-table-column
              prop="returnOut_TotalCount"
              label="数量"
              width="80"
              align="center"
            >
              <template #default="scope">
                <span
                  :class="{
                    'highlight-summary': scope.row.product_Number === '合计',
                  }"
                >
                  {{ formatNumber(scope.row.returnOut_TotalCount) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="returnOut_TotalAmount"
              label="金额"
              width="100"
              align="center"
            >
              <template #default="scope">
                <span
                  :class="{
                    'highlight-summary': scope.row.product_Number === '合计',
                  }"
                >
                  {{ formatCurrency(scope.row.returnOut_TotalAmount) }}
                </span>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <table>
        <tr>
          <td>
            <el-pagination
              v-model:current-page="pageQuery.pageindex"
              v-model:page-size="pageQuery.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot, sizes"
              :total="pageQuery.totalCount"
            >
              共{{ pageQuery.totalCount }}条 每页显示{{ pageQuery.pagesize }}条
              当前第{{ pageQuery.pageindex }}页/共{{ pageQuery.totalPage }}页
            </el-pagination>
          </td>
          <td>
            <el-pagination
              v-model:current-page="pageQuery.pageindex"
              v-model:page-size="pageQuery.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot, prev, pager, next"
              :total="pageQuery.totalCount"
              prev-text="上一页"
              next-text="下一页"
            >
              <el-button
                :disabled="pageQuery.pageindex == 1"
                @click="pageQuery.pageindex = 1"
                >首页</el-button
              >
            </el-pagination>
          </td>
          <td>
            <el-pagination
              v-model:current-page="pageQuery.pageindex"
              v-model:page-size="pageQuery.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot,jumper"
              :total="pageQuery.totalCount"
            >
              <el-button
                :disabled="pageQuery.pageindex == pageQuery.totalPage"
                @click="pageQuery.pageindex = pageQuery.totalPage"
                >尾页</el-button
              >
            </el-pagination>
          </td>
        </tr>
      </table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, reactive, watch, computed } from "vue";
import { ElMessage } from "element-plus";
import { Download, Refresh } from "@element-plus/icons-vue";
import * as echarts from "echarts";
import { BusinessRed } from "@/http/axiosHelper";
import type { ComponentSize } from "element-plus";
const size = ref<ComponentSize>("default");
import moment from "moment";

// 时间筛选选项
const timeFilters = ref([
  { key: "today", label: "今日" },
  { key: "yesterday", label: "昨日" },
  { key: "thisWeek", label: "本周" },
  { key: "lastWeek", label: "上周" },
  { key: "thisMonth", label: "本月" },
  { key: "lastMonth", label: "上月" },
  { key: "lastHalfYear", label: "最近半年" },
  { key: "lastYear", label: "最近一年" },
  { key: "custom", label: "自定义时间" },
]);

const selectedTimeFilter = ref("today");

// 自定义时间范围
const customDateRange = ref<[string, string] | null>(null);

// 图表引用
const inboundChart = ref<HTMLElement>();
const outboundChart = ref<HTMLElement>();

// 查询表单
const queryForm = reactive({
  startTime: "",
  endTime: "",
});

const pageQuery: any = reactive({
  pageindex: 1,
  pagesize: 15,
  totalCount: "",
  totalPage: "",
});
// 表格数据类型定义
interface TableDataItem {
  product_Id: number;
  product_Number: string;
  product_Name: string;
  specifications: string;
  category_ID: number;
  category_Name: string;
  // 入库数据
  purchaseIn_TotalCount: number;
  purchaseIn_TotalAmount: number;
  salesReturnIn_TotalCount: number;
  salesReturnIn_TotalAmount: number;
  productionIn_TotalCount: number;
  productionIn_TotalAmount: number;
  returnIn_TotalCount: number;
  returnIn_TotalAmount: number;
  // 出库数据
  salesOut_TotalCount: number;
  salesOut_TotalAmount: number;
  productionOut_TotalCount: number;
  productionOut_TotalAmount: number;
  returnOut_TotalCount: number;
  returnOut_TotalAmount: number;
  // 补充信息
  warehouseType: number;
  reviewer: string;
  reviewTime: string;
}

// 表格数据
const tableData = ref<TableDataItem[]>([]);

// 选中的行
const selectedRows = ref<any[]>([]);

// 加载状态
const loading = ref(false);

// 计算包含汇总行的表格数据
const tableDataWithSummary = computed(() => {
  if (tableData.value.length === 0) return [];

  // 创建汇总行
  const summaryRow: TableDataItem = {
    product_Id: 0,
    product_Number: "合计",
    product_Name: "",
    specifications: "",
    category_ID: 0,
    category_Name: "",
    // 入库数据汇总
    purchaseIn_TotalCount: getTotalInboundCount(),
    purchaseIn_TotalAmount: getTotalInboundAmount(),
    salesReturnIn_TotalCount: getTotalInboundCount(),
    salesReturnIn_TotalAmount: getTotalInboundAmount(),
    productionIn_TotalCount: getTotalInboundCount(),
    productionIn_TotalAmount: getTotalInboundAmount(),
    returnIn_TotalCount: getTotalInboundCount(),
    returnIn_TotalAmount: getTotalInboundAmount(),
    // 出库数据汇总
    salesOut_TotalCount: getTotalOutboundCount(),
    salesOut_TotalAmount: getTotalOutboundAmount(),
    productionOut_TotalCount: getTotalOutboundCount(),
    productionOut_TotalAmount: getTotalOutboundAmount(),
    returnOut_TotalCount: getTotalOutboundCount(),
    returnOut_TotalAmount: getTotalOutboundAmount(),
    // 补充信息
    warehouseType: 0,
    reviewer: "",
    reviewTime: "",
  };

  // 计算各列的具体汇总值
  summaryRow.purchaseIn_TotalCount = tableData.value.reduce(
    (sum, item) => sum + item.purchaseIn_TotalCount,
    0
  );
  summaryRow.purchaseIn_TotalAmount = tableData.value.reduce(
    (sum, item) => sum + item.purchaseIn_TotalAmount,
    0
  );
  summaryRow.salesReturnIn_TotalCount = tableData.value.reduce(
    (sum, item) => sum + item.salesReturnIn_TotalCount,
    0
  );
  summaryRow.salesReturnIn_TotalAmount = tableData.value.reduce(
    (sum, item) => sum + item.salesReturnIn_TotalAmount,
    0
  );
  summaryRow.productionIn_TotalCount = tableData.value.reduce(
    (sum, item) => sum + item.productionIn_TotalCount,
    0
  );
  summaryRow.productionIn_TotalAmount = tableData.value.reduce(
    (sum, item) => sum + item.productionIn_TotalAmount,
    0
  );
  summaryRow.returnIn_TotalCount = tableData.value.reduce(
    (sum, item) => sum + item.returnIn_TotalCount,
    0
  );
  summaryRow.returnIn_TotalAmount = tableData.value.reduce(
    (sum, item) => sum + item.returnIn_TotalAmount,
    0
  );

  summaryRow.salesOut_TotalCount = tableData.value.reduce(
    (sum, item) => sum + item.salesOut_TotalCount,
    0
  );
  summaryRow.salesOut_TotalAmount = tableData.value.reduce(
    (sum, item) => sum + item.salesOut_TotalAmount,
    0
  );
  summaryRow.productionOut_TotalCount = tableData.value.reduce(
    (sum, item) => sum + item.productionOut_TotalCount,
    0
  );
  summaryRow.productionOut_TotalAmount = tableData.value.reduce(
    (sum, item) => sum + item.productionOut_TotalAmount,
    0
  );
  summaryRow.returnOut_TotalCount = tableData.value.reduce(
    (sum, item) => sum + item.returnOut_TotalCount,
    0
  );
  summaryRow.returnOut_TotalAmount = tableData.value.reduce(
    (sum, item) => sum + item.returnOut_TotalAmount,
    0
  );

  return [...tableData.value, summaryRow];
});

onMounted(() => {
  search();
  initCharts();
});

// 方法
const selectTimeFilter = (key: string) => {
  selectedTimeFilter.value = key;

  // 根据选择的时间筛选设置查询参数
  const today = new Date();

  switch (key) {
    case "today":
      // 今日
      queryForm.startTime = today.toISOString().split("T")[0];
      queryForm.endTime = today.toISOString().split("T")[0];
      break;
    case "yesterday":
      // 昨日
      const yesterday = new Date(today);
      yesterday.setDate(today.getDate() - 1);
      queryForm.startTime = yesterday.toISOString().split("T")[0];
      queryForm.endTime = yesterday.toISOString().split("T")[0];
      break;
    case "thisWeek":
      // 本周
      const startOfWeek = new Date(today);
      startOfWeek.setDate(today.getDate() - today.getDay());
      const endOfWeek = new Date(startOfWeek);
      endOfWeek.setDate(startOfWeek.getDate() + 6);
      queryForm.startTime = startOfWeek.toISOString().split("T")[0];
      queryForm.endTime = endOfWeek.toISOString().split("T")[0];
      break;
    case "lastWeek":
      // 上周
      const lastWeekStart = new Date(today);
      lastWeekStart.setDate(today.getDate() - today.getDay() - 7);
      const lastWeekEnd = new Date(lastWeekStart);
      lastWeekEnd.setDate(lastWeekStart.getDate() + 6);
      queryForm.startTime = lastWeekStart.toISOString().split("T")[0];
      queryForm.endTime = lastWeekEnd.toISOString().split("T")[0];
      break;
    case "thisMonth":
      // 本月
      const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
      const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);
      queryForm.startTime = startOfMonth.toISOString().split("T")[0];
      queryForm.endTime = endOfMonth.toISOString().split("T")[0];
      break;
    case "lastMonth":
      // 上月
      const lastMonthStart = new Date(
        today.getFullYear(),
        today.getMonth() - 1,
        1
      );
      const lastMonthEnd = new Date(today.getFullYear(), today.getMonth(), 0);
      queryForm.startTime = lastMonthStart.toISOString().split("T")[0];
      queryForm.endTime = lastMonthEnd.toISOString().split("T")[0];
      break;
    case "lastHalfYear":
      // 最近半年
      const halfYearAgo = new Date(today);
      halfYearAgo.setMonth(today.getMonth() - 6);
      queryForm.startTime = halfYearAgo.toISOString().split("T")[0];
      queryForm.endTime = today.toISOString().split("T")[0];
      break;
    case "lastYear":
      // 最近一年
      const oneYearAgo = new Date(today);
      oneYearAgo.setFullYear(today.getFullYear() - 1);
      queryForm.startTime = oneYearAgo.toISOString().split("T")[0];
      queryForm.endTime = today.toISOString().split("T")[0];
      break;
    case "custom":
      // 自定义时间 - 清空日期范围，让用户手动选择
      queryForm.startTime = "";
      queryForm.endTime = "";
      break;
  }

  console.log(
    `选择时间筛选: ${key}, 日期范围: ${queryForm.startTime} 到 ${queryForm.endTime}`
  );

  // 如果不是自定义时间，重置页码并加载数据
  if (key !== "custom") {
    pageQuery.pageindex = 1;
    search();
  }
};

// 处理自定义时间范围变化
const handleCustomDateChange = (dates: [string, string] | null) => {
  if (dates && dates.length === 2) {
    queryForm.startTime = dates[0];
    queryForm.endTime = dates[1];
    console.log(`自定义时间范围: ${dates[0]} 到 ${dates[1]}`);
  }
};

// 使用自定义时间进行查询
const searchWithCustomDate = () => {
  if (customDateRange.value && customDateRange.value.length === 2) {
    queryForm.startTime = customDateRange.value[0];
    queryForm.endTime = customDateRange.value[1];
    pageQuery.pageindex = 1;
    search();
    ElMessage.success("自定义时间查询成功");
  } else {
    ElMessage.warning("请选择时间范围");
  }
};

const search = () => {
  loading.value = true;

  // 调用实际的API
  BusinessRed({
    url: "/api/Report/GetWareInOrOut_TypeSummary",
    method: "get",
    params: {
      startTime: queryForm.startTime,
      endTime: queryForm.endTime,
      pageindex: pageQuery.pageindex,
      pagesize: pageQuery.pagesize,
    },
  })
    .then((res: any) => {
      console.log("API返回数据:", res.data);

      // 处理API返回的数据，确保数据格式正确
      const processedData = processApiData(res.data.data || []);
      tableData.value = processedData;
      pageQuery.totalCount = res.data.totalCount || 0;
      pageQuery.totalPage = res.data.totalPage || 0;

      // 更新图表
      updateCharts();

      loading.value = false;
    })
    .catch((error: any) => {
      console.error("API调用失败:", error);
      // 如果API调用失败，使用模拟数据
      tableData.value = getMockData();
      ElMessage.warning("使用模拟数据");
      loading.value = false;
    });
};

watch(pageQuery, () => {
  search();
});

// 处理API返回的数据，确保数据格式正确并合并相同商品
const processApiData = (apiData: any[]): TableDataItem[] => {
  // 创建一个Map来存储合并后的数据
  const mergedData = new Map<string, TableDataItem>();

  apiData.forEach((item: any) => {
    const productKey =
      item.product_Number || item.productNumber || item.product_number || "";

    if (mergedData.has(productKey)) {
      // 如果商品已存在，则累加数据
      const existingItem = mergedData.get(productKey)!;

      // 累加入库数据
      existingItem.purchaseIn_TotalCount +=
        item.purchaseIn_TotalCount ||
        item.purchaseIn_TotalCount ||
        item.purchaseIn_TotalCount ||
        0;
      existingItem.purchaseIn_TotalAmount +=
        item.purchaseIn_TotalAmount ||
        item.purchaseIn_TotalAmount ||
        item.purchaseIn_TotalAmount ||
        0;

      existingItem.salesReturnIn_TotalCount +=
        item.salesReturnIn_TotalCount ||
        item.salesReturnIn_TotalCount ||
        item.salesReturnIn_TotalCount ||
        0;
      existingItem.salesReturnIn_TotalAmount +=
        item.salesReturnIn_TotalAmount ||
        item.salesReturnIn_TotalAmount ||
        item.salesReturnIn_TotalAmount ||
        0;

      existingItem.productionIn_TotalCount +=
        item.productionIn_TotalCount ||
        item.productionIn_TotalCount ||
        item.productionIn_TotalCount ||
        0;
      existingItem.productionIn_TotalAmount +=
        item.productionIn_TotalAmount ||
        item.productionIn_TotalAmount ||
        item.productionIn_TotalAmount ||
        0;

      existingItem.returnIn_TotalCount +=
        item.returnIn_TotalCount ||
        item.returnIn_TotalCount ||
        item.returnIn_TotalCount ||
        0;
      existingItem.returnIn_TotalAmount +=
        item.returnIn_TotalAmount ||
        item.returnIn_TotalAmount ||
        item.returnIn_TotalAmount ||
        0;

      // 累加出库数据
      existingItem.salesOut_TotalCount +=
        item.salesOut_TotalCount ||
        item.salesOut_TotalCount ||
        item.salesOut_TotalCount ||
        0;
      existingItem.salesOut_TotalAmount +=
        item.salesOut_TotalAmount ||
        item.salesOut_TotalAmount ||
        item.salesOut_TotalAmount ||
        0;

      existingItem.productionOut_TotalCount +=
        item.productionOut_TotalCount ||
        item.productionOut_TotalCount ||
        item.productionOut_TotalCount ||
        0;
      existingItem.productionOut_TotalAmount +=
        item.productionOut_TotalAmount ||
        item.productionOut_TotalAmount ||
        item.productionOut_TotalAmount ||
        0;

      existingItem.returnOut_TotalCount +=
        item.returnOut_TotalCount ||
        item.returnOut_TotalCount ||
        item.returnOut_TotalCount ||
        0;
      existingItem.returnOut_TotalAmount +=
        item.returnOut_TotalAmount ||
        item.returnOut_TotalAmount ||
        item.returnOut_TotalAmount ||
        0;
    } else {
      // 如果商品不存在，则创建新记录
      const newItem: TableDataItem = {
        product_Id: item.product_Id || item.productId || item.product_id || 0,
        product_Number: productKey,
        product_Name:
          item.product_Name || item.productName || item.product_name || "",
        specifications: item.specifications || item.specification || "",
        category_ID:
          item.category_ID || item.categoryId || item.category_id || 0,
        category_Name:
          item.category_Name || item.categoryName || item.category_name || "",

        // 入库数据
        purchaseIn_TotalCount:
          item.purchaseIn_TotalCount ||
          item.purchaseIn_TotalCount ||
          item.purchaseIn_TotalCount ||
          0,
        purchaseIn_TotalAmount:
          item.purchaseIn_TotalAmount ||
          item.purchaseIn_TotalAmount ||
          item.purchaseIn_TotalAmount ||
          0,

        salesReturnIn_TotalCount:
          item.salesReturnIn_TotalCount ||
          item.salesReturnIn_TotalCount ||
          item.salesReturnIn_TotalCount ||
          0,
        salesReturnIn_TotalAmount:
          item.salesReturnIn_TotalAmount ||
          item.salesReturnIn_TotalAmount ||
          item.salesReturnIn_TotalAmount ||
          0,

        productionIn_TotalCount:
          item.productionIn_TotalCount ||
          item.productionIn_TotalCount ||
          item.productionIn_TotalCount ||
          0,
        productionIn_TotalAmount:
          item.productionIn_TotalAmount ||
          item.productionIn_TotalAmount ||
          item.productionIn_TotalAmount ||
          0,

        returnIn_TotalCount:
          item.returnIn_TotalCount ||
          item.returnIn_TotalCount ||
          item.returnIn_TotalCount ||
          0,
        returnIn_TotalAmount:
          item.returnIn_TotalAmount ||
          item.returnIn_TotalAmount ||
          item.returnIn_TotalAmount ||
          0,

        // 出库数据
        salesOut_TotalCount:
          item.salesOut_TotalCount ||
          item.salesOut_TotalCount ||
          item.salesOut_TotalCount ||
          0,
        salesOut_TotalAmount:
          item.salesOut_TotalAmount ||
          item.salesOut_TotalAmount ||
          item.salesOut_TotalAmount ||
          0,

        productionOut_TotalCount:
          item.productionOut_TotalCount ||
          item.productionOut_TotalCount ||
          item.productionOut_TotalCount ||
          0,
        productionOut_TotalAmount:
          item.productionOut_TotalAmount ||
          item.productionOut_TotalAmount ||
          item.productionOut_TotalAmount ||
          0,

        returnOut_TotalCount:
          item.returnOut_TotalCount ||
          item.returnOut_TotalCount ||
          item.returnOut_TotalCount ||
          0,
        returnOut_TotalAmount:
          item.returnOut_TotalAmount ||
          item.returnOut_TotalAmount ||
          item.returnOut_TotalAmount ||
          0,

        // 补充信息
        warehouseType: item.warehouseType || item.warehouse_type || 0,
        reviewer: item.reviewer || "",
        reviewTime: item.reviewTime || item.review_time || "",
      };

      mergedData.set(productKey, newItem);
    }
  });

  return Array.from(mergedData.values());
};

const updateCharts = () => {
  // 根据实际数据更新图表
  // 这里可以根据tableData来生成图表数据
  console.log("更新图表数据");

  // 计算各类型的汇总数据用于图表显示
  const inboundSummary = {
    purchaseReceive: 0,
    salesReturn: 0,
    productionProduct: 0,
    usageReturn: 0,
  };

  const outboundSummary = {
    sales: 0,
    productionUsage: 0,
    usageReturn: 0,
  };

  tableData.value.forEach((item) => {
    // 入库汇总
    inboundSummary.purchaseReceive += item.purchaseIn_TotalCount;
    inboundSummary.salesReturn += item.salesReturnIn_TotalCount;
    inboundSummary.productionProduct += item.productionIn_TotalCount;
    inboundSummary.usageReturn += item.returnIn_TotalCount;

    // 出库汇总
    outboundSummary.sales += item.salesOut_TotalCount;
    outboundSummary.productionUsage += item.productionOut_TotalCount;
    outboundSummary.usageReturn += item.returnOut_TotalCount;
  });

  // 更新图表数据
  updateChartData(inboundSummary, outboundSummary);
};

// 更新图表数据的函数
const updateChartData = (inboundSummary: any, outboundSummary: any) => {
  // 计算入库数据的最大值，用于动态调整Y轴
  const inboundData = [
    inboundSummary.purchaseReceive,
    inboundSummary.salesReturn,
    inboundSummary.productionProduct,
    inboundSummary.usageReturn,
  ];
  const maxInbound = Math.max(...inboundData, 1); // 至少为1，避免除以0

  // 计算合理的Y轴最大值和间隔
  const calculateYAxis = (maxValue: number) => {
    // 根据最大值计算合适的Y轴最大值
    let max = Math.ceil(maxValue * 1.2);

    // 确保最大值是25的倍数，这样间隔会更整齐
    max = Math.ceil(max / 25) * 25;

    // 如果最大值小于25，则设置为25
    if (max < 25) max = 25;

    // 计算间隔，优先使用25作为间隔
    let interval = 25;

    // 如果最大值较小，使用更小的间隔
    if (max <= 50) {
      interval = 10;
    } else if (max <= 100) {
      interval = 25;
    } else if (max <= 200) {
      interval = 25;
    } else if (max <= 500) {
      interval = 50;
    } else {
      interval = Math.ceil(max / 10);
    }

    return { max, interval };
  };

  const inboundYAxis = calculateYAxis(maxInbound);

  // 更新入库图表
  if (inboundChart.value) {
    const inboundChartInstance = echarts.getInstanceByDom(inboundChart.value);
    if (inboundChartInstance) {
      inboundChartInstance.setOption({
        yAxis: {
          max: inboundYAxis.max,
          interval: inboundYAxis.interval,
        },
        series: [
          {
            data: inboundData,
          },
        ],
      });
    }
  }

  // 计算出库数据的最大值，用于动态调整Y轴
  const outboundData = [
    outboundSummary.sales,
    outboundSummary.productionUsage,
    outboundSummary.usageReturn,
  ];
  const maxOutbound = Math.max(...outboundData, 1); // 至少为1，避免除以0

  const outboundYAxis = calculateYAxis(maxOutbound);

  // 更新出库图表
  if (outboundChart.value) {
    const outboundChartInstance = echarts.getInstanceByDom(outboundChart.value);
    if (outboundChartInstance) {
      outboundChartInstance.setOption({
        yAxis: {
          max: outboundYAxis.max,
          interval: outboundYAxis.interval,
        },
        series: [
          {
            data: outboundData,
          },
        ],
      });
    }
  }
};

const initCharts = () => {
  nextTick(() => {
    // 初始化入库图表
    if (inboundChart.value) {
      const inboundChartInstance = echarts.init(inboundChart.value);
      const inboundOption = {
        title: {
          text: "入库类型汇总",
          left: "center",
          textStyle: {
            fontSize: 16,
            fontWeight: "bold",
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: function (params: any) {
            return `${params[0].name}<br/>${params[0].seriesName}: ${params[0].value}`;
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: [
            "采购收货入库",
            "销售退货入库",
            "生产产品入库",
            "领用退还入库",
          ],
          axisLabel: {
            rotate: 45,
          },
        },
        yAxis: {
          type: "value",
          name: "数量",
          min: 0,
          max: 100,
          interval: 25,
          axisLabel: {
            formatter: "{value}",
          },
        },
        series: [
          {
            name: "数量",
            type: "bar",
            data: [0, 0, 0, 0],
            itemStyle: {
              color: "#67C23A",
            },
            barWidth: "40%",
            label: {
              show: true,
              position: "top",
              formatter: "{c}",
            },
          },
        ],
      };
      inboundChartInstance.setOption(inboundOption);
    }

    // 初始化出库图表
    if (outboundChart.value) {
      const outboundChartInstance = echarts.init(outboundChart.value);
      const outboundOption = {
        title: {
          text: "出库类型汇总",
          left: "center",
          textStyle: {
            fontSize: 16,
            fontWeight: "bold",
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: function (params: any) {
            return `${params[0].name}<br/>${params[0].seriesName}: ${params[0].value}`;
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: ["销售出库", "生产领用出库", "领用退还出库"],
          axisLabel: {
            rotate: 45,
          },
        },
        yAxis: {
          type: "value",
          name: "数量",
          min: 0,
          max: 100,
          interval: 25,
          axisLabel: {
            formatter: "{value}",
          },
        },
        series: [
          {
            name: "数量",
            type: "bar",
            data: [0, 0, 0],
            itemStyle: {
              color: "#409EFF",
            },
            barWidth: "40%",
            label: {
              show: true,
              position: "top",
              formatter: "{c}",
            },
          },
        ],
      };
      outboundChartInstance.setOption(outboundOption);
    }
  });
};

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
  console.log("选中的行:", selection.length, "条");
};

// 为汇总行添加特殊样式
const getRowClassName = ({ row }: { row: TableDataItem }) => {
  if (row.product_Number === "合计") {
    return "summary-row";
  }
  return "";
};

// 为汇总行单元格添加特殊样式
const getCellClassName = ({
  row,
  column,
}: {
  row: TableDataItem;
  column: any;
}) => {
  if (row.product_Number === "合计") {
    return "summary-cell";
  }
  return "";
};

// 判断行是否可选择（汇总行不可选择）
const isRowSelectable = (row: TableDataItem) => {
  return row.product_Number !== "合计";
};

//导出
async function exportData() {
  try {
    // 准备导出参数
    const exportParams: any = {
      startTime: queryForm.startTime,
      endTime: queryForm.endTime,
      pageindex: pageQuery.pageindex,
      pagesize: pageQuery.pagesize,
    };

    // 如果有选中的行，添加选中行的ID列表
    if (selectedRows.value.length > 0) {
      const selectedIds = selectedRows.value.map(
        (row: any) => row.product_Id || row.product_Number
      );
      exportParams.selectedIds = selectedIds;
      console.log("导出选中的数据:", selectedRows.value.length, "条");
    } else {
      console.log("导出全部数据");
    }

    // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
    const response = await BusinessRed({
      url: "/api/Report/loadWareInOrOut_TypeSummary", // 后端接口地址
      method: "GET",
      params: exportParams, // 对应后端 [FromQuery] 的 command 参数
      responseType: "blob", // 关键：指定响应类型为二进制流（Excel 文件）
    });

    // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
    const fileName = getFileNameFromHeaders(response.headers);

    // 3. 生成下载链接并触发下载
    const blob = new Blob([response.data], {
      type:
        response.headers["content-type"] ||
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = fileName; // 文件名从响应头获取或自定义
    document.body.appendChild(a);
    a.click();

    // 4. 清理资源
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
  } catch (error: any) {
    // 处理错误（如后端返回 401/400 等）
    console.error("导出失败：", error.response?.data || error.message);
    alert("导出失败，请检查参数或重新登录");
  }
}

// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers: any) {
  const contentDisposition =
    headers["content-disposition"] || headers["Content-Disposition"];
  if (!contentDisposition) return "出入库类型汇总信息列表.xlsx"; // 默认文件名

  // 解码文件名（处理中文编码问题）
  const match = contentDisposition.match(/filename\*?=([^;]+)/);
  if (match) {
    return decodeURIComponent(match[1].replace(/["']/g, ""));
  }
  return "出入库类型汇总信息列表.xlsx";
}

const refreshData = () => {
  ElMessage.success("数据已刷新");
  search();
};

const handleSizeChange = (val: number) => {
  pageQuery.pagesize = val;
  search();
};

const handleCurrentChange = (val: number) => {
  pageQuery.pageindex = val;
  search();
};

// 格式化函数
const formatNumber = (value: number): string => {
  if (value === null || value === undefined) return "0";
  return value.toLocaleString();
};

const formatCurrency = (value: number): string => {
  if (value === null || value === undefined) return "¥0.00";
  return `¥${value.toFixed(2)}`;
};

// 汇总计算函数
const getTotalInboundCount = (): number => {
  return tableData.value.reduce((total, item) => {
    return (
      total +
      item.purchaseIn_TotalCount +
      item.salesReturnIn_TotalCount +
      item.productionIn_TotalCount +
      item.returnIn_TotalCount
    );
  }, 0);
};

const getTotalInboundAmount = (): number => {
  return tableData.value.reduce((total, item) => {
    return (
      total +
      item.purchaseIn_TotalAmount +
      item.salesReturnIn_TotalAmount +
      item.productionIn_TotalAmount +
      item.returnIn_TotalAmount
    );
  }, 0);
};

const getTotalOutboundCount = (): number => {
  return tableData.value.reduce((total, item) => {
    return (
      total +
      item.salesOut_TotalCount +
      item.productionOut_TotalCount +
      item.returnOut_TotalCount
    );
  }, 0);
};

const getTotalOutboundAmount = (): number => {
  return tableData.value.reduce((total, item) => {
    return (
      total +
      item.salesOut_TotalAmount +
      item.productionOut_TotalAmount +
      item.returnOut_TotalAmount
    );
  }, 0);
};

// 生成模拟数据
const getMockData = (): TableDataItem[] => {
  return [
    {
      product_Id: 1,
      product_Number: "T002",
      product_Name: "电池",
      specifications: "1",
      category_ID: 1,
      category_Name: "电子产品",
      // 入库数据
      purchaseIn_TotalCount: 36,
      purchaseIn_TotalAmount: 1332.0,
      salesReturnIn_TotalCount: 120,
      salesReturnIn_TotalAmount: 2540.0,
      productionIn_TotalCount: 0,
      productionIn_TotalAmount: 0.0,
      returnIn_TotalCount: 0,
      returnIn_TotalAmount: 0.0,
      // 出库数据
      salesOut_TotalCount: 0,
      salesOut_TotalAmount: 0.0,
      productionOut_TotalCount: 0,
      productionOut_TotalAmount: 0.0,
      returnOut_TotalCount: 0,
      returnOut_TotalAmount: 0.0,
      // 补充信息
      warehouseType: 1,
      reviewer: "赵姝雅",
      reviewTime: "2025-08-15T15:24:29",
    },
    {
      product_Id: 2,
      product_Number: "T003",
      product_Name: "华为手机",
      specifications: "Mate 60 Pro",
      category_ID: 1,
      category_Name: "电子产品",
      // 入库数据
      purchaseIn_TotalCount: 45,
      purchaseIn_TotalAmount: 450.0,
      salesReturnIn_TotalCount: 25,
      salesReturnIn_TotalAmount: 250.0,
      productionIn_TotalCount: 35,
      productionIn_TotalAmount: 350.0,
      returnIn_TotalCount: 18,
      returnIn_TotalAmount: 180.0,
      // 出库数据
      salesOut_TotalCount: 55,
      salesOut_TotalAmount: 550.0,
      productionOut_TotalCount: 30,
      productionOut_TotalAmount: 300.0,
      returnOut_TotalCount: 12,
      returnOut_TotalAmount: 120.0,
      // 补充信息
      warehouseType: 1,
      reviewer: "管理员",
      reviewTime: "2025-08-15T10:30:00",
    },
    {
      product_Id: 3,
      product_Number: "T004",
      product_Name: "小米手机",
      specifications: "Redmi Note 13",
      category_ID: 1,
      category_Name: "电子产品",
      // 入库数据
      purchaseIn_TotalCount: 80,
      purchaseIn_TotalAmount: 800.0,
      salesReturnIn_TotalCount: 15,
      salesReturnIn_TotalAmount: 150.0,
      productionIn_TotalCount: 25,
      productionIn_TotalAmount: 250.0,
      returnIn_TotalCount: 10,
      returnIn_TotalAmount: 100.0,
      // 出库数据
      salesOut_TotalCount: 70,
      salesOut_TotalAmount: 700.0,
      productionOut_TotalCount: 20,
      productionOut_TotalAmount: 200.0,
      returnOut_TotalCount: 8,
      returnOut_TotalAmount: 80.0,
      // 补充信息
      warehouseType: 1,
      reviewer: "系统",
      reviewTime: "2025-08-15T09:15:00",
    },
  ];
};
</script>

<style scoped>
.ware-in-out-type-summary {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.time-filter-card {
  margin-bottom: 20px;
}

.time-filter {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
}

.custom-time-picker {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-left: 10px;
}

.charts-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.chart-container {
  height: 350px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart {
  width: 100%;
  height: 100%;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 表格样式优化 */
.el-table {
  font-size: 14px;
}

.el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.el-table td {
  padding: 8px 0;
}

/* 数字列右对齐 */
.el-table .cell {
  text-align: center;
}

/* 多级表头样式 */
.el-table .el-table__header-wrapper .el-table__header th {
  border-right: 1px solid #ebeef5;
}

.el-table .el-table__header-wrapper .el-table__header th:last-child {
  border-right: none;
}

/* 表头层级样式 */
.el-table .el-table__header-wrapper .el-table__header th.is-leaf {
  background-color: #fafafa;
}

.el-table .el-table__header-wrapper .el-table__header th:not(.is-leaf) {
  background-color: #f5f7fa;
  font-weight: bold;
}

/* 汇总行样式 */
.summary-row {
  background-color: #ffffff !important;
  font-weight: bold;
}

.summary-row td {
  background-color: #ffffff !important;
  color: #1e40af;
  font-weight: bold;
  border: none !important;
}

.summary-row:hover td {
  background-color: #ffffff !important;
}

/* 汇总文本样式 */
.summary-text {
  color: #1e40af;
  font-weight: bold;
}

/* 汇总数据黄色高亮样式 */
.highlight-summary {
  color: #f59e0b !important;
  font-weight: bold;
  text-align: center;
}

/* 汇总行单元格样式 */
.summary-cell {
  border: none !important;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .charts-container {
    /* 已经是上下布局，无需额外调整 */
  }
}

@media (max-width: 768px) {
  .ware-in-out-type-summary {
    padding: 10px;
  }

  .time-filter {
    justify-content: center;
  }

  .table-header {
    flex-direction: column;
    gap: 10px;
  }
}
</style>
